package com.wiscom.portal.demo.service.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;

import com.wiscom.pagination.JdbcDaoSupportWithPagination;
import com.wiscom.portal.demo.entity.Jc;
import com.wiscom.portal.demo.service.JcService;

/**
 * JcService的实现类
 * author:yyu date:2011-7-19
 */
public class JcServiceImpl extends JdbcDaoSupportWithPagination implements JcService {

	@SuppressWarnings("unchecked")
	@Override
	public List<Jc> query(Map<String,Object> params) {
		StringBuffer sql = new StringBuffer();
		sql.append("select jcdm,jcmc,cbrq,zz from t_jc ");
		if(params.get("query_jcmc") != null){ 	//当查询条件不为空，在查询sql中加入过滤
			sql.append("where jcmc like '%" + params.get("query_jcmc") + "%' ");
		}
		sql.append(" order by jcdm "); 
		return getJdbcTemplateWithPagination().queryWithPagination(sql.toString(), new JcRowMapper());
	}

	private class JcRowMapper implements RowMapper{
		public Jc mapRow(ResultSet rs,int rownum) throws SQLException {
			Jc jc = new Jc();
			jc.setJcdm(rs.getString(1));
			jc.setJcmc(rs.getString(2));
			jc.setCbrq(rs.getDate(3));
			jc.setZz(rs.getString(4));
			return jc;
		}
	}

	@Override
	public void insert(final Jc jc) {
		String sql = "insert into t_jc(jcdm,jcmc,cbrq,zz) values(?,?,?,?)";
		getJdbcTemplate().update(sql, new PreparedStatementSetter(){
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, jc.getJcdm());
				ps.setString(2, jc.getJcmc());
				if(jc.getCbrq() == null){
					ps.setDate(3, null);
				} else {
					ps.setDate(3, new java.sql.Date(jc.getCbrq().getTime()));
				}
				ps.setString(4, jc.getZz());
			}
		});
	}

	@Override
	public void update(final Jc jc) {
		String sql = "update t_jc set jcmc = ?,cbrq = ?,zz = ? where jcdm = ?";
		getJdbcTemplate().update(sql, new PreparedStatementSetter(){
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, jc.getJcmc());
				if(jc.getCbrq() == null){
					ps.setDate(2, null);
				} else {
					ps.setDate(2, new java.sql.Date(jc.getCbrq().getTime()));
				}
				ps.setString(3, jc.getZz());
				ps.setString(4, jc.getJcdm());
			}
		});
	}

	@Override
	public Jc getJc(String jcdm) {
		return (Jc) getJdbcTemplate().queryForObject(
                "select jcdm,jcmc,cbrq,zz from t_jc where jcdm = ? ",
                new Object[]{jcdm},
                new JcRowMapper());
	}

	@Override
	public void deleteJc(String jcdm) {
		String sql = "delete from t_jc where jcdm = ? ";
		getJdbcTemplate().update(sql, new Object[]{jcdm});
	}
	
	
	
}
